"use strict";
define(["commonUI", "laydate", "template", "drawer","global", "validate", "select2", "datatables", "plupload"], function (
    commonUI, laydate, template, Drawer,global
) {
    var user = null;
    var projectId=1;
    //传给后台的参数
    var param = {
        pageNumber: 1,
        pageSize: 10
    };
    var table21 = "";
    var app = {
        init: function () {
            user = global.getLoginUser();
            $(".username").text(user.userName)
            this.eventBind();
            this.initSelect();
            this.renderTable();
            this.intDrawer();
        },
        // 筛选项初始化
        initSelect: function () {
            global.get("/admin/project/listByUser",function (res) {
                if (res.success) {
                    var demoData = [];
                    var projects = res.data.projects;
                    var flag = false;
                    projects.forEach(item=>{
                        var m = {};
                        m.id = item.id;
                        m.text = item.name;
                        if(flag==false){
                            m.selected=true;
                            flag = true;
                            projectId = item.id;
                        }
                        demoData.push(m);
                    })
                    $("#relatePro").select2({
                        width: "222px",
                        data:demoData,
                        minimumResultsForSearch: -1
                    });
                    $("#relatePro").on("change",function(){
                        var data = $(this).val();
                        projectId = data;
                        table21.ajax.reload();
                    });
                } 
            },);
        },
        // 渲染表格
        renderTable: function () {
            table21 = $('#standard_table').DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                ordering: false,
                serverSide: true,
                destroy: true,
                // scrollX: true,
                columns: [{
                    title: '<div id="select-checkbox" class="select-checkbox1"></div>',
                    data: "checkBox",
                    width: 20,
                    render:function(){
                        return "";
                    }
                }, {
                    title: '序号',
                    data: "number",
                    width: 30
                }, {
                    title: '点位名称',
                    data: "name",
                    width: 120
                },{
                    title: '所属项目',
                    data: "projectName",
                    width: 120
                }, {
                    title: '智能网关',
                    data: "gatewayName",
                    width: 120

                }, {
                    title: '单位',
                    data: "unit",
                    width: 30,
                }, {
                    title: '通讯站号',
                    data: "communicationStation",
                    width: 20

                }, {
                    title: '监测周期',
                    data: "period",
                    width: 40,
                    render(data){
                        return data/60 + "分钟"
                    }
                },{
                    title: '设定值',
                    data: "stdValue",
                    width: 40,
                    render(data){
                        if(data==null || data.trim()==""){
                            return "-";
                        }else{
                            return data;
                        }
                    }
                }
                // , {
                //     title: '启用状态',
                //     data: "status",
                //     width: 40,
                //     render: function (data) {
                //         if(data==1) {
                //             return '<span class="state-lable start-state">启用</span>'
                //             // return '<span class="btn-switch btn-multiple-state">'+
                //             //         '<span class="btn-state checked">启用</span>'+
                //             //         '<span class="btn-state">停用</span>'+
                //             //     '</span>'
                //         } else {
                //             return '<span class="state-lable stop-state">停用</span>'
                //             // return '<span class="btn-switch btn-multiple-state">'+
                //             //         '<span class="btn-state">启用</span>'+
                //             //         '<span class="btn-state checked">停用</span>'+
                //             //     '</span>'
                //         }
                //     },
                // }
                ,{
                    title: '操作',
                    orderable: false,
                    width: 150,
                    render: function (data, type, full) {
                        return '<a class="edit" data-id="' + full.id + '">编辑</a>' +
                            '<a class="del-single" data-id="' + full.id + '">删除</a>'
                    },
                }],
                lengthMenu: [[15, 25, 50, 100], ["15条/页", "25条/页", "50条/页", "100条/页"]],
                columnDefs: [{
                    className: 'select-checkbox ',
                    targets: 0
                }, {
                    targets: [1, 2, 3, 4, 5, 6, 7, 8],
                    render: function (data) {//其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                select: {
                    // 可选择的配置有： 'api'、'single'、'multi'、'os'、'multi+shift'
                    style: 'multi',
                    // 控制是否在左下角显示选中信息
                    info: false,
                    selector: 'td:first-child',
                    orderable: false
                },
                order: [],
                language: {
                    sEmptyTable: '<div class="blank-icon"><p class="msg"><i class="aidicon aidicon-emoticon-sad"></i> 没有搜到任何数据</p></div>'
                },
                ajax: function (params, callback, setting) {
                    // 表格逻辑
                    $('#standard_table_wrapper thead>tr>.select-checkbox').removeClass('selected');
                    $("#delete_all").prop("disabled", true);
                    //排序参数
                    var sortType = "",
                        sortName = "";
                    if (params.order.length > 0) {
                        sortType = params.order[0].dir;
                        sortName = params.columns[params.order[0].column].data;
                    }
                    param.pageNumber = (params.start / params.length) + 1;
                    param.pageSize = params.length;
                    param.projectId = projectId;
                    param.keyword = $("#search_val").val()
                    global.get("/admin/device/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param);
                },
                initComplete: function (settings, json) {
                    var html = '<li data-curIndex="all" class="all-col"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">全部展示</span></label></div></li>';
                    for (var i = 0; i < settings.aoColumns.length; i++) {
                        if (i == 0) {
                            html += '<li data-curIndex="' + i + '"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">勾选列</span></label></div></li>';
                        } else {
                            html += '<li data-curIndex="' + i + '"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">' + settings.aoColumns[i].sTitle + '</span></label></div></li>';
                        }

                    }
                    $(".dropdown-col-menu").append(html);
                    $('.dropdown-col-menu>li input').change(function () {
                        if ($(this).closest('li').attr('data-curIndex') == "all") { //点击全部
                            if ($(this).is(':checked')) {
                                table21.columns().visible(true);
                                $(this).closest('li').siblings('li').find('input').prop("checked", true)
                            } else {
                                table21.columns().visible(false);
                                $(this).closest('li').siblings('li').find('input').prop("checked", false)
                            }
                        } else { //点击每一列
                            var _index = parseInt($(this).closest('li').attr('data-curIndex'), 10);
                            if ($(this).is(':checked')) {
                                table21.columns(_index).visible(true);
                            } else {
                                table21.columns(_index).visible(false);
                            }

                            // 控制全选的样式
                            var colLength = table21.columns().count();
                            var colSelect = $('.dropdown-col-menu > li[data-curIndex != all] input:checked').length;
                            if (colSelect == colLength) {
                                $('.dropdown-col-menu .all-col input').prop("checked", true);
                            } else {
                                $('.dropdown-col-menu .all-col input').prop("checked", false);
                            }
                        }
                    });

                    //计算列定制下拉的位置
                    var leftPx = "-" + ($(".dropdown-col-menu").width() - 30) + "px";
                    $(".dropdown-col-menu").css("left", leftPx);

                }
            });

            // 去掉选中
            table21.on('deselect', function (e, dt, type, indexs) {
                // $(e.target).find('thead>tr>.select-checkbox').removeClass('selected');
                $(e.target).closest('.dataTables_scroll').find('.dataTables_scrollHead').find('thead>tr>.select-checkbox').removeClass('selected');
                var selectedLength = table21.rows({
                    selected: true
                }).count();
                if (selectedLength == 0) {
                    $("#export").prop("disabled", true);
                    $("#delete_all").prop("disabled", true);
                    $(".dropdown-opt-con .btn").prop("disabled", true);
                }
            });
            // 点击全选
            $('#standard_table_wrapper .select-checkbox1').click(function (e) {

                var $parent = $(this).parent('th');
                $parent.toggleClass('selected');
                if ($parent.hasClass('selected')) {
                    $(this).parents('#standard_table_wrapper').find('tbody tr').each(function (i) {
                        table21.row(i).select()
                    });
                } else {
                    $(this).parents('#standard_table_wrapper').find('tbody tr').each(function (i) {
                        table21.row(i).select(false)
                    });
                }
            });
            // 勾选其中一项
            table21.on('select', function (e, dt, type, indexs) {
                // 选中行数
                var selectedLength = table21.rows({
                    selected: true
                }).count();
                $("#export").prop("disabled", false);
                $("#delete_all").prop("disabled", false);
                $(".dropdown-opt-con .btn").prop("disabled", false);
                // 所有行数行数
                var allLength = table21.rows().count();
                // selectedLength === allLength && $(e.target).find('thead>tr>.select-checkbox').addClass('selected');
                selectedLength === allLength && $(e.target).closest('.dataTables_scroll').find('.dataTables_scrollHead').find('thead>tr>.select-checkbox').addClass('selected');
            });
        },
        //抽屉
        intDrawer: function () {
            // 新增抽屉
            var addDrawerOpts = {
                title: "",
                data: {},
                content: template("addFormTpl"),
                onClosed:function () {
                },
                button: [
                    {
                        label: "取消",
                        intent: "default",
                        click:function () {
                            app.addDrawer.close();
                        }
                    },
                    {
                        label: "提交",
                        intent: "primary",
                        click: function () {
                            if (!$(".addForm").valid()) {
                                return false;
                            }
                            var data = {};
                            data.id = $("#id").val()
                            data.name =$("#name").val()
                            data.tag =$("#tag").val()
                            data.communicationStation = $("#communicationStation").val()
                            data.gatewayId = $("#gatewayId").val() 
                            data.templateId = $("#unitId").val()
                            data.projectId = projectId;
                            data.period = 300;
                            data.number = $("#number").val()
                            data.status = $(".status.checked").attr("value");
                            data.display = $(".display.checked").attr("value");
                            data.stdValue = $("#stdValue").val();
                            data.runningWarning=$(".runningWarning.checked").attr("value");
                            console.log(data)
                            global.post("/admin/device/saveOrUpdate",response=>{
                                if(response.success){
                                    app.addDrawer.close();
                                    table21.ajax.reload(null,false);
                                }else{
                                    alert(response.message)
                                }
                            },JSON.stringify(data))
                        }
                    }
                ]
            };
            app.addDrawer = new Drawer(addDrawerOpts);
        },
        /** 事件绑定 */
        eventBind: function () {
            // 新增
            $('#add').on('click', function () {
                var content = template("addFormTpl", {data:{status:1,display:1}});
                app.addDrawer.renderOption({title: "新增",content:content});
                app.addDrawer.open();
                var gateways = [];
                var units = [];
                var periods = [];
                global.get("/admin/gateway/listAll",function (res) {
                    if (res.success) {
                        res.data.gateways.forEach(item=>{
                            var m = {};
                            m.id = item.id;
                            m.text = item.name;
                            gateways.push(m);
                        });
                    } 
                },null,null,false);
                global.get("/admin/device/unit/listAll",function (res) {
                    if (res.success) {
                        res.data.units.forEach(item=>{
                            var m = {};
                            m.id = item.id;
                            m.text = item.name + " " + item.tag;
                            units.push(m);
                        });
                    }  
                },null,null,false);
                var periods = [
                    {
                        id: "1",
                        text: "5分钟"
                    },
                    {
                        id: "2",
                        text: "10分钟"
                    },
                    {
                        id: "1",
                        text: "15分钟"
                    },
                    {
                        id: "2",
                        text: "30分钟"
                    },{
                        id: "1",
                        text: "1小时"
                    }
                ];
                $("#gatewayId").select2({
                    data:gateways,
                    minimumResultsForSearch: -1
                });
                $("#unitId").select2({
                    data:units,
                    minimumResultsForSearch: -1
                });
                $("#period").select2({
                    data:periods,
                    minimumResultsForSearch: -1
                });
            });
            // 编辑
            $(document).on("click", ".edit", function () {
                var deviceId = $(this).attr("data-id");
                var editInfo = null;
                global.get("/admin/device/"+deviceId,function(response){
                    if(response.success){
                        editInfo = response.data.device;
                    }else{
                        alert(response.message);
                    }
                },null,null,false);
                var content = template("addFormTpl", {data: editInfo});
                app.addDrawer.renderOption({title: "修改", content: content});
                app.addDrawer.open();
                var gateways = [];
                var units = [];
                var periods = [];
                global.get("/admin/gateway/listAll",function (res) {
                    if (res.success) {
                        res.data.gateways.forEach(item=>{
                            var m = {};
                            m.id = item.id;
                            m.text = item.name;
                            if(editInfo.gatewayId==item.id){
                                m.selected=true;
                            }
                            gateways.push(m);
                        });
                    } 
                },null,null,false);
                global.get("/admin/device/unit/listAll",function (res) {
                    if (res.success) {
                        res.data.units.forEach(item=>{
                            var m = {};
                            m.id = item.id;
                            m.text = item.name + " " + item.tag;
                            if(editInfo.unitId==item.id){
                                m.selected=true;
                            }
                            units.push(m);
                        });
                    }  
                },null,null,false);
                var periods = [
                    {
                        id: "1",
                        text: "5分钟"
                    },
                    {
                        id: "2",
                        text: "10分钟"
                    },
                    {
                        id: "1",
                        text: "15分钟"
                    },
                    {
                        id: "2",
                        text: "30分钟"
                    },{
                        id: "1",
                        text: "1小时"
                    }
                ];
                $("#gatewayId").select2({
                    data:gateways,
                    minimumResultsForSearch: -1
                });
                $("#unitId").select2({
                    data:units,
                    minimumResultsForSearch: -1
                });
                $("#period").select2({
                    data:periods,
                    minimumResultsForSearch: -1
                });
            });
            // 单个删除
            $(document).on('click', ".del-single", function () {
                var deviceId = $(this).attr("data-id");
                Dialog.open({
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确定删除该信息吗？</span>",
                    width: 320,
                    height: 'auto',
                    modal: true,
                    content: '<div class="padding-left-large-5">您确定要删除吗？删除后状态不可恢复。</div>',
                    button: [
                        { id: "mybtn1", label: "确认", intent: "primary", focus: true, click: function () { 
                            global.delete("/admin/device/delete/"+deviceId,response=>{
                                if(response.success){
                                    app.addDrawer.close();
                                    table21.ajax.reload(null,false);
                                }else{
                                    alert(response.message);
                                }
                            })
                        } },
                        { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                });
            });
            // 批量删除
            $(document).on('click', "#delete_all", function () {
                Dialog.open({
                    id: "delete_all_dialog",
                    theme: "simple-dialog",
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>您确定要删除所选内容吗？</span>",
                    width: 420,
                    height: 'auto',
                    modal: true,
                    content: '<div class="padding-left-large-5"><div class="font-color-weak padding-horizontal-large-2 padding-bottom-large-2">删除后的数据将无法恢复</div></div>',
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var pripidDom = table21.rows('.selected').data()
                            var ids = [];
                            Array.prototype.slice.call(pripidDom).forEach(function(v, i) {
                                ids.push(v.id);
                            });
                            global.delete("/admin/device/deletems/"+ids.join("&"),response=>{
                                if(response.success){
                                    table21.ajax.reload(null,false);
                                }else{
                                    alert(response.message);
                                }
                            })
                            // var pripidDom = table21.rows('.selected').data(),
                            //     taskIdArr = [],
                            //     taskNameArr = [];
                            // Array.prototype.slice.call(pripidDom).forEach(function(v, i) {
                            //     taskIdArr.push(v.id);
                            //     taskNameArr.push(v.taskName);
                            // });
                            // var param = {
                            //     taskId: taskIdArr.join(","),
                            //     taskName: taskNameArr.join(",")
                            // };
                            // $.ajax({
                            //     url: "",
                            //     type: "get",
                            //     data: param,
                            //     dataType: "json",
                            //     success: function(res) {
                            //         table21.ajax.reload();
                            //     }
                            // });
                        }
                    }, {
                        id: "mybtn2",
                        label: "取消",
                        click: function () {

                        }
                    }]
                });
            });
            // 搜索筛选
            $(".aidicon-magnify").on("click", function () {
                var searchVal = $("#search_val").val();
                console.log(searchVal);
                param.keyword = searchVal;
                table21.ajax.reload();
            });
            $("#search_val").on("keyup", function (event) {
                if (event.keyCode == "13") {
                    var searchVal = $("#search_val").val();
                    console.log(searchVal);
                    param.keyword = searchVal;
                    table21.ajax.reload();
                }
            });
            //去掉搜索框内容
            $('.searchbox .aidicon-close').on('mousedown', function () {
                $(this).siblings('input').val('');
            });
        }

    };
    return app;
});